<template>
    <div>
        <van-form @submit="onSubmit">
            <van-cell-group inset class="cell">
                <van-field v-model="tel" name="手机号" label="手机号" placeholder="手机号"
                    :rules="[{ required: true, message: '请填写手机号' }]" @blur="phoneCheck" />
                <van-field v-model="sms" center clearable label="短信验证码" placeholder="请输入短信验证码"
                    :rules="[{ required: true, message: '请填写短信验证码' }]">
                    <template #button>
                        <van-button size="small" type="primary" @click="smsVer" :disabled="disabled">发送验证码</van-button>
                    </template>
                </van-field>
                <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
                    :rules="[{ required: true, message: '请填写密码' }]" />
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit">
                    提交
                </van-button>
            </div>
        </van-form>
    </div>
</template>
<script lang='ts' setup>
import { ref } from 'vue';
import { register, smsRequst, smsCheck, telCheck } from '@/service/api';
import { showNotify } from 'vant';
import 'vant/es/notify/style';
import router from '@/router';
const password = ref('');
const tel = ref('');
const sms = ref('');
const disabled = ref(true)
async function phoneCheck() {
    if (/^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/.test(tel.value)) {
        const result = await telCheck(tel.value);
        if (result.data.code === '200') {
            disabled.value = false
        } else {
            showNotify({ type: 'danger', message: result.data.message })
            disabled.value = true
        }
    } else {
        showNotify({ type: 'danger', message: '请输入正确的手机号' })
    }
}
async function smsVer() {
    const result = await smsRequst(tel.value);
    showNotify({ type: 'success', message: result.data.message })
}
async function onSubmit() {
    const result = await smsCheck(tel.value, sms.value);
    if (result.data.code === '200') {
        const res = await register(tel.value, password.value);
        showNotify({ type: 'success', message: res.data.message, duration: 1500 });
        router.push('/login');
    } else {
        showNotify({ type: 'danger', message: result.data.message })
    }

}
</script>
<style scoped>
.cell {
    margin: 0;
    margin-top: 15px;
    border-radius: 0;
}
</style>